<?php

namespace App\Admin\Controllers\Act;

use App\Http\Controllers\Controller;
use App\Model\Gift;
use App\Model\WishTreeGift;
use App\Util\InfoUtil;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Grid;
use Encore\Admin\Form;
use Encore\Admin\Layout\Content;

class WishTreeGiftController extends Controller
{
    use ModelForm;

    public function index()
    {
        $content = new Content();
        $content->header('许愿树礼物配置');
        $content->body($this->grid());
        return $content;
    }

    public function edit($id)
    {
        $content = new Content();
        $content->header('编辑');
        $content->body($this->form()->edit($id));
        return $content;
    }

    public function create()
    {
        $content = new Content();
        $content->header('创建');
        $content->body($this->form());
        return $content;
    }

    protected function grid()
    {
        $grid = new Grid(new WishTreeGift());
        $grid->model()->orderBy('id', 'desc');
        // $grid->id('配置ID')->sortable();
        $grid->giftInfo()->id('礼物ID')->sortable();
        $grid->giftInfo()->name('礼物名')->sortable();
        $grid->giftInfo()->coin('礼物价值')->sortable();
        $grid->giftInfo()->order_index('排序')->sortable();
        $grid->gift_percent('礼物概率')->editable();
        $grid->gift_num('礼物数量')->editable();
        $grid->flag('状态')->display(function ($data) {
            return $data == 1 ? '有效' : '无效';
        });
        //禁用导出
        $grid->disableExport();
        //禁用行选择
        $grid->disableRowSelector();
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableView();
        });
        return $grid;
    }

    protected function form()
    {
        $form = new Form(new WishTreeGift());
        $form->column(1 / 2, function ($form) {
            $form->text('gift_percent', '概率')->required();
            $form->text('gift_num', '礼物数量')->default(0)->required();
        });
        $form->column(1 / 2, function ($form) {
            $form->select('gift_id', '礼物')->options(Gift::getList([3, 4]));
            $form->select('flag', '是否有效')->options([1 => '有效', 0 => '无效'])->default(1)->required();
        });
        $form->saving(function (Form $form) {
            if (floatval($form->gift_percent) >= 1) return InfoUtil::adminErr('概率设置错误');
        });
        return $form;
    }
}
